package com.stage.communication;
import com.stage.helper.InputManager;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
/**
 * Created by Stage on 2017/3/24.
 */
public class ServiceInput implements Runnable {
    private InputManager inputManager = new InputManager();
    private ArrayList<Socket> clients = new ArrayList<>();
    public ServiceInput(ArrayList<Socket> clients) {
        this.clients = clients;
    }
    @Override
    public void run() {
        while (true) {
            String clientInput = inputManager.inputString("客服请输入您要输入的话(输入1私聊)：   ");
            for (Socket client : clients
                    ) {
                try {
                    if (clientInput.equals("1")) {
                        String port = inputManager.inputString("请输入客户编号：   ");
                        Object[] targetClient = clients.stream().filter(s -> s.getPort() == Integer.valueOf(port)).toArray();
                        try {
                            Socket currentClient = (Socket) targetClient[0];
                            clientInput = inputManager.inputString("客服请输入您要私聊的话：   ");
                            PrintWriter writer = new PrintWriter(currentClient.getOutputStream());
                            writer.println(clientInput);
                            writer.flush();
                            clientInput = "";
                        } catch (Exception e) {
                            System.out.println("该客户已下线或不存在！");
                            clientInput = "";
                        }
                    } else {
                        PrintWriter writer = new PrintWriter(client.getOutputStream());
                        writer.println(clientInput);
                        writer.flush();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
